package cn.edu.nju.software.cdiy.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.nju.software.cdiy.bean.User;
import cn.edu.nju.software.cdiy.dao.UserDao;

public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public User updateUser(User user) {
		Session session = sessionFactory.getCurrentSession();
		try {
			if(user!=null)
			session.update(user);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return user;
	}

	@Override
	public User updateRegistor(User user)  {
		if (checkExist(user)) {
			return null;
		} else {
			Session session = sessionFactory.getCurrentSession();
			try {
				session.save(user);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			return user;
		}
	}

	private boolean checkExist(User user) {
		Session session = sessionFactory.getCurrentSession();
		boolean returnBoolean = false;
		try {
			Query query = session.createQuery("from User u where u.name=:username");
			query.setString("username", user.getName());
			List list = query.list();
			if (list.size() != 0) {
				returnBoolean = true;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return returnBoolean;
	}

	
	@Override
	public User getUserById(Long id) {
		Session session = sessionFactory.getCurrentSession();
		User returnUser = null;
		try {
			returnUser=(User) session.load(User.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return returnUser;
	}

	

	@Override
	public User login(User user) {
		Session session = sessionFactory.getCurrentSession();
		User returnUser = null;
		try {
			Query query = session
					.createQuery("from User  a where a.name=:username and a.password=:userpassword");
			query.setString("username", user.getName());
			query.setString("userpassword", user.getPassword());
			List list = query.list();
			if (list.size() != 0)
				returnUser = (User) list.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return returnUser;
	}
}
